<?php
function httpRequest($url, $method="GET", $postfields = null, $headers = array(), $debug = false)
{
    $method = strtoupper($method);
    $ci = curl_init();
    /* Curl settings */
    curl_setopt($ci, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
    curl_setopt($ci, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.2; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0");
    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, 60); /* 在发起连接前等待的时间，如果设置为0，则无限等待 */
    curl_setopt($ci, CURLOPT_TIMEOUT, 7); /* 设置cURL允许执行的最长秒数 */
    curl_setopt($ci, CURLOPT_RETURNTRANSFER, true);
    switch ($method) {
        case "POST":
            curl_setopt($ci, CURLOPT_POST, true);
            if (!empty($postfields)) {
                $tmpdatastr = is_array($postfields) ? http_build_query($postfields) : $postfields;
                curl_setopt($ci, CURLOPT_POSTFIELDS, $tmpdatastr);
            }
            break;
        default:
            curl_setopt($ci, CURLOPT_CUSTOMREQUEST, $method); /* //设置请求方式 */
            break;
    }
    $ssl = preg_match('/^https:\/\//i', $url) ? TRUE : FALSE;
    curl_setopt($ci, CURLOPT_URL, $url);
    if ($ssl) {
        curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, FALSE); // https请求 不验证证书和hosts
        curl_setopt($ci, CURLOPT_SSL_VERIFYHOST, FALSE); // 不从证书中检查SSL加密算法是否存在
    }
    //curl_setopt($ci, CURLOPT_HEADER, true); /*启用时会将头文件的信息作为数据流输出*/
    if (ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) {
        curl_setopt($ci, CURLOPT_FOLLOWLOCATION, 1);
    }
    curl_setopt($ci, CURLOPT_MAXREDIRS, 2);/*指定最多的HTTP重定向的数量，这个选项是和CURLOPT_FOLLOWLOCATION一起使用的*/
    curl_setopt($ci, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ci, CURLINFO_HEADER_OUT, true);
    /*curl_setopt($ci, CURLOPT_COOKIE, $Cookiestr); * *COOKIE带过去** */
    $response = curl_exec($ci);
    $requestinfo = curl_getinfo($ci);
    $http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
    if ($debug) {
        echo "=====post data======\r\n";
        var_dump($postfields);
        echo "=====info===== \r\n";
        print_r($requestinfo);
        echo "=====response=====\r\n";
        print_r($response);
    }
    // curl_close($ci);
    return $response;
    //return array($http_code, $response,$requestinfo);
}

//批量查询关键词最高排名
function getTaskid($domainName,$keywords){

        $url = C('rank')['url'];
        $key = C('rank')['key'];
        // $domainName = 'chinaz.com';
        // $keywords = '站长|站长之家';
        foreach ($url as $k => $v) {
            $arr = array(
                'key' =>  C('rank')['key'],
                'domainName' =>  $domainName,
                'keywords' =>  $keywords,
                
            );
            if(json_decode(httpRequest($v,'post',$arr),true)['StateCode'] == 1){
                $list[] = json_decode(httpRequest($v,'post',$arr),true)['TaskID'];
            }else{
                $list[] = json_decode(httpRequest($v,'post',$arr),true);
                $num = 1;
            }
            
        }
        sleep(12);
        if($num == 1){
            return $list;
        }
        $result = getRank($list);
        // $list = array(
        //     "d122fc379cca439b8bc71f3c",
        //     "4ba2bc43a7f640a0890b2d2a",
        //     "270ace73b08e4a40b8695ef2",
        //     "c8e9e60847cc4ff4b2bebafc",
        //     "7d06d0f695164d229154bc78",
        //     "67766b66257448179ca5665b",
        // );
        // $result['rank'] = getRank($list);
        // $result['list'] = $list;
        return $result;
    }

function getRank($arr){
    $getApi = C('rank')['GetApi'];
    $q=1;
    foreach ($arr as $key => $v) {
        $data = array(
            'taskid' => $v,
        );
        // $datalist = json_decode(httpRequest($getApi,'post',$data),true)['Result']['Data'];
        $datalists = json_decode(httpRequest($getApi,'post',$data),true);
        if($datalists['StateCode'] != 1){
            $result[$q] = $datalists['Result'];
            $q++;
            continue;
        }
        $datalist = $datalists['Result']['Data'];
        $arrs = [];
        foreach ($datalist as $k => $v) {
            $rk = str_replace('-','',$v['Result']['Ranks'][0]['RankStr']);
            $arrs[] = array(
                'keyword' => $v['Keyword'],
                'Rank' => intval($rk) > 0 ? intval($rk)-10 : 51,
            );
            // $result[$q] = intval($rk)-10;
            // $q++;
        }
        $result[$q] = $arrs;
        $q++;
        
    }
    return $result;
}

//单个关键词排名查询
function oneRank($keyword,$domainName){
// function oneRank(){
    // $url = C('rank')['oneUrl']['baiduPc'];
    $url = C('rank')['oneUrl'];
    $q = 1;
    // $keyword = '站长';
    // $domainName = 'chinaz.com';
    $key = C('rank')['key'];
    $data = array(
        'key' => $key,
        'domainName' => $domainName,
        'keyword' => $keyword,
    );
    foreach ($url as $key => $v) {
        $datalist = json_decode(httpRequest($v,'post',$data),true)['Result']['Ranks'];
        $rk = str_replace('-','',$datalist[0]['RankStr']);
        $result[$q] = intval($rk) > 0 ? intval($rk)-10 : 51;
        $q++;
    }

    return $result;  
}


//单个关键词单个搜索引擎排名查询
function oneRankSeo($keyword,$domainName,$seo){
    $url = C('rank')['oneUrl'][$seo];
    // $keyword = '站长';
    // $domainName = 'chinaz.com';
    $key = C('rank')['key'];
    $data = array(
        'key' => $key,
        'domainName' => $domainName,
        'keyword' => $keyword,
    );
    $datalist = json_decode(httpRequest($v,'post',$data),true)['Result']['Ranks'];
    $rk = str_replace('-','',$datalist[0]['RankStr']);
    $result = intval($rk) > 0 ? intval($rk)-10 : 51;
    return $result;  
}

//关键词百度指数
function zhishou($keyword){
    $url = C('index')[0];
    $key = C('rank')['key'];
    $data = array(
        'key' => $key,
        'keyword' => $keyword,
    );
    $datalist = json_decode(httpRequest($url,'post',$data),true);
    if($datalist['StateCode'] == 1 && !empty($datalist['Result'])){
        $num = explode(',',$datalist['Result']['BaiduPc']);
        return round(array_sum($num)/30,2);
    }else{
        logs(json_encode($datalist));
        return 0;
    } 
}

//关键词百度收录量
function shoulu($keyword){
    $url = C('number')[0];
    $key = C('rank')['key'];
    $data = array(
        'key' => $key,
        'keyword' => $keyword,
    );
    $datalist = json_decode(httpRequest($url,'post',$data),true);
    if($datalist['StateCode'] == 1 && $datalist['Result']){
        return $datalist['Result']['CollectCount']/10000000;
    }else{
        logs(json_encode($datalist));
        return 0;
    } 
}

function logs($content, $subDir = ''){
    $subDir = trim($subDir, '/\\');
    if (empty($content)) return false;
    static $arrConfig = array();
    if (empty($arrConfig)){
        $arrPath  = array(MODULE_NAME, CONTROLLER_NAME, ACTION_NAME);
        $arrConfig['root_path'] = './error_log/';
        $arrConfig['sub_dir']   = implode('/', $arrPath);
        $arrConfig['file_name'] = '/' . date('Ymd') . '.log';
        $arrConfig['client_ip'] = get_client_ip();
        $arrConfig['logs_no']   = date('ymdHis') . microtime() * 1000000;
    }

    $filepath = $arrConfig['root_path'];
    if ($subDir){
        $filepath .= $subDir ;
    } else {
        $filepath .= $arrConfig['sub_dir'] ;
    }

    if (!file_exists($filepath)){
        mkdir($filepath, 0777, TRUE);
    }

    $filepath .= $arrConfig['file_name'];

    $header = sprintf("\r\n\r\n[%s][%s][%s] ", date('Y-m-d H:i:s'), $arrConfig['client_ip'],$arrConfig['logs_no']);
    @file_put_contents($filepath, $header . $content, FILE_APPEND);

    return $arrConfig['logs_no'] ;
}


function price_back($kwd){
    $today = strtotime('yesterday');
    $where['logtime'] = array('gt',$today);
    $where['Keyword'] = array('eq',$kwd);
    $where['baiduipc'] = array('neq',0);
    $price = M('keyword')->where($where)->find();
    if($price){
        $amount = $price['baiduipc']/2;
        return $amount;
    }else{
       // $kwds = str_replace("公司","",$kwd);
       $strlen = mb_strlen($kwd,'UTF8');
       if($strlen == 1){
            $amount = 20+20*(shoulu($kwd));
       }elseif($strlen == 2){
            $amount = 15+15*(shoulu($kwd));
       }elseif($strlen == 3){
            $amount = 10+10*(shoulu($kwd));
       }elseif($strlen == 4){
            $amount = 9+9*(shoulu($kwd));
       }elseif($strlen == 5){
            $amount = 6+6*(shoulu($kwd));
       }elseif($strlen == 6){
            $amount = 5+5*(shoulu($kwd));
       }elseif($strlen == 7){
            $amount = 4.5+4.5*(shoulu($kwd));
       }elseif($strlen == 8){
            $amount = 4.25+4.25*(shoulu($kwd));
       }elseif($strlen == 9){
            $amount = 4+4*(shoulu($kwd));
       }elseif($strlen == 10){
            $amount = 3.85+3.85*(shoulu($kwd));
       }else{
            $amount = 3.5+3.5*(shoulu($kwd));
       }
       logs($kwds.'--'.$kwd.'--'.$strlen);
       return round($amount,2);
    }
}














function getExcel($fileName,$headArr,$data){
    Vendor('PHPExcel.Classes.PHPExcel');
    $objPHPExcel = new \PHPExcel();

    $date = date("Y_m_d", time());
    $fileName .= "_{$date}.xls";
    //创建PHPExcel对象，注意，不能少了\
    $objPHPExcel = new \PHPExcel();
   
    $objProps = $objPHPExcel->getProperties();

    //设置表头
    $key = ord("A");
    foreach ($headArr as $v) {
        $colum = chr($key);
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
        $key += 1;

    }
    $column = 2;
    $objActSheet = $objPHPExcel->getActiveSheet();

    foreach ($data as $key => $rows) { //行写入
        $span = ord("A");

        foreach ($rows as $keyName => $value) {// 列写入
            $j = chr($span);
            $objActSheet->setCellValue($j . $column, $value);
            $span++;

        }
        $column++;

    }
    $objPHPExcel->getActiveSheet()->getColumnDimension("A")->setAutoSize(true);
    $objPHPExcel->getActiveSheet()->getColumnDimension("B")->setAutoSize(true);
    $objPHPExcel->getActiveSheet()->getColumnDimension("C")->setAutoSize(true);
    $objPHPExcel->getActiveSheet()->getColumnDimension("D")->setAutoSize(true);
    $objPHPExcel->getActiveSheet()->getColumnDimension("F")->setAutoSize(true);
    $fileName = iconv("utf-8", "gb2312", $fileName);
    //重命名表
    // $objPHPExcel->getActiveSheet()->setTitle('test');
    //设置活动单指数到第一个表,所以Excel打开这是第一个表
    $objPHPExcel->setActiveSheetIndex(0);
    ob_end_clean();
    ob_start();
    header('Content-Type: application/vnd.ms-excel');
    header("Content-Disposition: attachment;filename=\"$fileName\"");
    header('Cache-Control: max-age=0');
    $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output'); //文件通过浏览器下载
    exit;
}